package com.kaibes.im.model;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import com.kaibes.im.utils.ByteStringUtil;

public class KaibesFile extends File {

    /**
     * v1.0
     */
    private static final long serialVersionUID = 1L;

    private FileOutputStream fileOutputStream;
    private String type;
    private int targetSize;

    public KaibesFile(String filepath) {
	super(filepath);
	init();
    }

    public KaibesFile(File filefolder, String filename) {
	super(filefolder, filename);
	init();
    }

    private void init() {

	if (!this.getParentFile().exists()) {
	    this.getParentFile().mkdirs();
	}

    }

    public KaibesFile open() {
	try {
	    this.fileOutputStream = new FileOutputStream(this, true);
	} catch (FileNotFoundException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}

	return this;
    }

    public void write2File(String content) {
	ByteStringUtil.string2FosBase64(content, getFileOutputStream());
    }

    public boolean isComplete() {
	if (this.length() < targetSize) {
	    return false;
	}

	return true;
    }

    public void close() {
	try {
	    if (fileOutputStream != null) {
		this.fileOutputStream.close();
	    }
	} catch (IOException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
    }

    public void cacheRenameToFile(File parent) {
	close();
	File file = new File(parent, getParentFile().getName() + File.separator
		+ getName());
	if (!file.getParentFile().exists()) {
	    file.getParentFile().mkdir();
	}
	renameTo(file);
    }

    public FileOutputStream getFileOutputStream() {
	return fileOutputStream;
    }

    public int getTargetSize() {
	return targetSize;
    }

    public void setTargetSize(int targetSize) {
	this.targetSize = targetSize;
    }

    public String getType() {
	return type;
    }

    public void setType(String type) {
	this.type = type;
    }

}
